package com.qymerge.manage.core.utils;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;

public class SHA256Enhanced {

    /**
     * 生成带盐值的 SHA-256 哈希
     * @param input 原始字符串
     * @param salt 盐值字节数组（可为 null）
     * @return Base64 编码的哈希值
     */
    public static String hashWithSalt(String input, byte[] salt) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            if (salt != null) md.update(salt); // 添加盐值
            byte[] hashBytes = md.digest(input.getBytes());
            return Base64.getEncoder().encodeToString(hashBytes);
        } catch (Exception e) {
            throw new RuntimeException("Hashing failed", e);
        }
    }

    // 生成随机盐（推荐 16 字节）
    public static byte[] generateSalt() {
        byte[] salt = new byte[16];
        new SecureRandom().nextBytes(salt);
        return salt;
    }

    public static String sha256(String  password) {
        byte[] salt = generateSalt(); // 存储时需保留此盐值
        String hashed = hashWithSalt(password, null);
        System.out.println("加盐哈希 (Base64): " + hashed);
        return  hashed;
    }

    public static void main(String[] args) {
        String s = sha256("123456");
        //ZTsJ0RP2PuCGJwtChILcS19+GpPn/pjCGylbfwe07mE=
        //FL6azQsvoHKWLVU35fgON2jhP/3hUKadOZhHAKpSjc0=
        // vPqdNSCOr/h9PRee0FY2sLZZFXkmFY48ZFwWBaDH1D8=
        // vPqdNSCOr/h9PRee0FY2sLZZFXkmFY48ZFwWBaDH1D8=
        System.out.println(s);
    }

}
